package com.zhijian.medical.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhijian.medical.dao.local.FishAnShiMapper;
import com.zhijian.medical.dao.local.FishReportMapper;
import com.zhijian.medical.entity.dto.JqyzqkDto;
import com.zhijian.medical.entity.po.*;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.enums.*;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author li xiao dong
 * @since 2022-08-12
 */
@Service
public class FishAnShiServiceImpl extends ServiceImpl<FishAnShiMapper, ExperimentFishAn> implements FishAnShiService {
    @Autowired
    private FishAnShiMapper anMapper;

    @Autowired
    private FishAnShiJieguoService anJieguoService;

    @Autowired
    private FishService fishService;

    @Autowired
    private ExperimentProcessSampleService sampleService;

    @Autowired
    private FishReportService reportService;

    @Autowired
    private FishReportMapper reportMapper;

    @Autowired
    private ExperimentProcessSampleLogService sampleLogService;

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public Boolean create(ExperimentFishAn experimentFishAn) {
        deleteAnByFishId(experimentFishAn.getFishId());
        Long anId = insert(experimentFishAn);
        for (ExperimentFishAnJieguo experimentFishAnJieguo : experimentFishAn.getJudgeRecord()) {
            experimentFishAnJieguo.setAnId(anId);
            anJieguoService.insert(experimentFishAnJieguo);
            anJgcl(experimentFishAnJieguo);
        }

        //修改整个实验的状态
        fishService.updateByPrimaryKeySelective(ExperimentFish.builder().id(experimentFishAn.getFishId()).status(ExperimentFishStatusEnum.AS.getCode().byteValue()).build());

        List<ExperimentProcessSampleVo> sampleVoList = sampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.FISH.getCode().byteValue())
                .experimentProcessId(experimentFishAn.getFishId())
                .build());
        ExperimentFish fish = fishService.detail(experimentFishAn.getFishId());
        sampleLogService.saveBatch(sampleVoList.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(experimentFishAn.getFishId())
                .mainType(ExperimentTypeEnum.FISH.getCode().byteValue())
                .op(String.format("%s%s-%s", fish.getName(), fish.getExperimentNum(), ExperimentFishStatusEnum.AS.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

    /**
     * 处理样本的方式
     *
     * @param experimentFishAnJieguo
     * @return
     */
    public Boolean anJgcl(ExperimentFishAnJieguo experimentFishAnJieguo) {
        Byte jgcl = experimentFishAnJieguo.getJgcl();
        if (jgcl == null) {
            return true;
        }
        byte status = 0;
        //发报告
        if (jgcl == ExperimentFishAnJgclEnum.FBG.getCode().byteValue()) {
            status = 7;
            createReport(experimentFishAnJieguo);
        }
        //重送样本
        if (jgcl == ExperimentFishAnJgclEnum.CXSY.getCode().byteValue()) {
            status = 4;
        }
        //重新杂交
        if (jgcl == ExperimentFishAnJgclEnum.CXZJ.getCode().byteValue()) {
            status = 6;
        }
        //退费
        if (jgcl == ExperimentFishAnJgclEnum.TF.getCode().byteValue()) {
            status = 8;
        }
        if (status == 0) {
            return true;
        }
        ExperimentProcessSample processSample = new ExperimentProcessSample();
        processSample.setStatus(status);
        processSample.setMoleculePathologyNumber(experimentFishAnJieguo.getFzblh());
        return sampleService.updateByPrimaryKeySelective(processSample);

    }

    private Boolean createReport(ExperimentFishAnJieguo experimentFishAnJieguo) {
        QueryWrapper<ExperimentFishReport> experimentFishReportQueryWrapper = new QueryWrapper<>();
        experimentFishReportQueryWrapper.eq("fzblh", experimentFishAnJieguo.getFzblh());
        experimentFishReportQueryWrapper.eq("jcxm", experimentFishAnJieguo.getXm());
        ExperimentFishReport fishReport = reportMapper.selectOne(experimentFishReportQueryWrapper);

        if (fishReport == null) {
            fishReport = new ExperimentFishReport();
        }
        //样本
        ExperimentProcessSample processSample = sampleService.selectByFzblh(experimentFishAnJieguo.getFzblh());
        fishReport.setName(processSample.getName());
        fishReport.setSex(Integer.valueOf(processSample.getSex()));
        fishReport.setMzh(processSample.getMzh());
        fishReport.setAge(processSample.getAge());
        fishReport.setZyh(processSample.getZyh());
        fishReport.setCh(processSample.getCh());
        fishReport.setDoctor(processSample.getDoctor());
        fishReport.setHospital(processSample.getHospital());
        fishReport.setInfectedPatch(processSample.getInfectedPatch());
        fishReport.setKb(processSample.getKb());
        fishReport.setJcxm(experimentFishAnJieguo.getXm());
        fishReport.setFzblh(experimentFishAnJieguo.getFzblh());
        fishReport.setJcff("荧光原位杂交法");
        fishReport.setJsjqxb(String.valueOf(experimentFishAnJieguo.getJsxb()));
        fishReport.setRstbz(experimentFishAnJieguo.getHer2rst());
        fishReport.setRstxhsxhhsjz(experimentFishAnJieguo.getRstxb());
        fishReport.setHer2xhsjz(experimentFishAnJieguo.getHer2xhsjz());
        fishReport.setFishId(experimentFishAnJieguo.getFishId());
        //检测位点，如果是HER2的话
        if (experimentFishAnJieguo.getXm().equals(ExperimentTypeEnum.FISH.getProject().get(0))) {
            fishReport.setJcwd("红色荧光信号标记Her-2，青色荧光信号标记17号染色体");
            fishReport.setHer2xhlx(experimentFishAnJieguo.getXhlx() == 0 ? "簇状" : "点状");
        }
        //标本类型
        fishReport.setBblx(processSample.getType());
        //诊断
        fishReport.setZd(experimentFishAnJieguo.getJgms() == 0 ? "阳性" : "阴性");
        //肿瘤异质性
        fishReport.setZlxbycxyzx(experimentFishAnJieguo.getZlyzx() == 1 ? "一般" : "差");
        //监测区域
        fishReport.setJcqy("肿瘤浸润区");
        //免疫组化
        fishReport.setMyzh(experimentFishAnJieguo.getMyzhher2());
        return reportService.update(fishReport);

    }

    @Override
    public ExperimentFishAn detail(Long fishId) {
        ExperimentFishAn experimentFishAn = selectOne(fishId);
        if (!StrUtil.isBlankIfStr(experimentFishAn.getJqyzqks())) {
            experimentFishAn.setJqyzqk(JSONObject.parseArray(experimentFishAn.getJqyzqks(), JqyzqkDto.class));
        }
        experimentFishAn.setJudgeRecord(anJieguoService.list(fishId));
        ExperimentFish experimentFish = fishService.selectByPrimaryKey(fishId);
        experimentFishAn.setResult(experimentFish.getStatus() >= ExperimentFishStatusEnum.AS.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        experimentFishAn.setResultStr(experimentFish.getStatus() >= ExperimentFishStatusEnum.AS.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        return experimentFishAn;
    }


    public ExperimentFishAn selectOne(Long fishId) {
        QueryWrapper<ExperimentFishAn> experimentFishAnQueryWrapper = new QueryWrapper<>();
        experimentFishAnQueryWrapper.eq("fish_id", fishId);
        return anMapper.selectOne(experimentFishAnQueryWrapper);
    }

    @Override
    public Long insert(ExperimentFishAn experimentFishAn) {
        experimentFishAn.setJqyzqks(JSON.toJSONString(experimentFishAn.getJqyzqk()));
        int count = anMapper.insert(experimentFishAn);
        if (count <= 0) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "暗室创建失败");
        }
        return experimentFishAn.getId();
    }

    public Boolean deleteAnByFishId(Long fishId) {
        delete(fishId);
        anJieguoService.deleteByFishId(fishId);
        return true;
    }

    public Boolean delete(Long fishId) {
        QueryWrapper<ExperimentFishAn> experimentFishAnQueryWrapper = new QueryWrapper<>();
        experimentFishAnQueryWrapper.eq("fish_id", fishId);
        return anMapper.delete(experimentFishAnQueryWrapper) > 0;
    }
}
